<template>
  <div class="order-payment">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>库存调拨审核</h1>
      <div class="breadcrumb">仓库管理 > 库存调拨审核</div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <div class="search-form">
        <div class="form-item">
          <label>调拨单号</label>
          <input v-model="searchForm.transferCode" type="text" placeholder="请输入调拨单号" @input="onSearchInput" />
        </div>
        <div class="form-item">
          <label>调出仓库</label>
          <select v-model="searchForm.fromWarehouseId" @change="fetchAuditList">
            <option value="">全部</option>
            <option v-for="item in warehouses" :key="item.id" :value="item.id">{{ item.whName }}</option>
          </select>
        </div>
        <div class="form-item">
          <label>调入仓库</label>
          <select v-model="searchForm.toWarehouseId" @change="fetchAuditList">
            <option value="">全部</option>
            <option v-for="item in warehouses" :key="item.id" :value="item.id">{{ item.whName }}</option>
          </select>
        </div>
        <div class="form-item">
          <label>调拨类型</label>
          <select v-model="searchForm.transferType" @change="fetchAuditList">
            <option value="">全部</option>
            <option value="内部调拨">内部调拨</option>
            <option value="外部调拨">外部调拨</option>
          </select>
        </div>
        <div class="form-item">
          <label>创建人</label>
          <input v-model="searchForm.createdBy" type="text" placeholder="请输入创建人" @input="onSearchInput" />
        </div>
        <div class="form-item">
          <label>提交日期</label>
          <input v-model="searchForm.submitDate" type="date" @change="fetchAuditList" />
        </div>
        <div class="form-buttons">
          <button class="btn btn-primary" @click="fetchAuditList">查询</button>
          <button class="btn btn-secondary" @click="resetSearch">重置</button>
        </div>
      </div>
    </div>

    <!-- 审核说明 -->
    <div class="audit-info-bar">
      <div class="info-text">
        <span class="info-icon">ℹ️</span>
        点击"审核"按钮可查看调拨详情并进行审核决策
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <div class="stat-card audit">
        <div class="stat-number">{{ auditList.length }}</div>
        <div class="stat-label">待审核调拨单</div>
      </div>
      <div class="stat-card audit">
        <div class="stat-number">{{ totalItems }}</div>
        <div class="stat-label">涉及商品数</div>
      </div>
      <div class="stat-card audit">
        <div class="stat-number">{{ totalAmount }}</div>
        <div class="stat-label">总调拨金额</div>
      </div>
      <div class="stat-card audit">
        <div class="stat-number">{{ auditList.length }}</div>
        <div class="stat-label">本页记录</div>
      </div>
    </div>

    <!-- 待审核调拨单列表 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
        <tr>
          <th>序号</th>
          <th>调拨单号</th>
          <th>调出仓库</th>
          <th>调入仓库</th>
          <th>调拨类型</th>
          <th>创建人</th>
          <th>提交时间</th>
          <th>商品数量</th>
          <th>调拨金额</th>
          <th>优先级</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="item in auditList" :key="item.id">
          <td>{{ item.id }}</td>
          <td>
            <div class="transfer-code">{{ item.transferCode }}</div>
            <div class="transfer-meta">{{ item.id }}</div>
          </td>
          <td>{{ getWarehouseName(item.fromWarehouseId) }}</td>
          <td>{{ getWarehouseName(item.toWarehouseId) }}</td>
          <td>{{ item.transferType || '-' }}</td>
          <td>{{ item.createdBy || '-' }}</td>
          <td>{{ formatDate(item.createdAt) }}</td>
          <td>{{ item.itemCount || 0 }}</td>
          <td>¥{{ formatAmount(item.totalAmount) }}</td>
          <td>
            <span :class="getPriorityClass(item.priority)">{{ getPriorityText(item.priority) }}</span>
          </td>
          <td>
            <button class="btn btn-small btn-primary" @click="handleAudit(item)">审核</button>
          </td>
        </tr>
        <tr v-if="auditList.length === 0">
          <td colspan="11" class="text-center">暂无待审核的调拨单</td>
        </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="pagination.total > 0">
      <div class="pagination-info">
        共{{ Math.ceil(pagination.total / pagination.size) }}页/{{ pagination.total }}条数据
      </div>
      <div class="pagination-controls">
        <button class="btn btn-page" :disabled="pagination.current === 1" @click="changePage(pagination.current - 1)">上一页</button>
        <button
            v-for="page in visiblePages"
            :key="page"
            class="btn btn-page"
            :class="{ active: page === pagination.current }"
            @click="changePage(page)"
        >
          {{ page }}
        </button>
        <button class="btn btn-page" :disabled="pagination.current === Math.ceil(pagination.total / pagination.size)" @click="changePage(pagination.current + 1)">下一页</button>
      </div>
    </div>

    <!-- 调拨详情审核对话框 -->
    <div v-if="auditDetailDialog.visible" class="modal-overlay" @click="auditDetailDialog.visible = false">
      <div class="modal-content audit-modal" @click.stop>
        <div class="modal-header">
          <h3>调拨审核详情 - {{ auditDetailDialog.data.transfer?.transferCode }}</h3>
          <button class="modal-close" @click="auditDetailDialog.visible = false">&times;</button>
        </div>
        <div class="modal-body">
          <!-- 调拨单基本信息 -->
          <div class="audit-summary">
            <div class="summary-row">
              <div class="summary-item">
                <span class="label">调出仓库：</span>
                <span>{{ getWarehouseName(auditDetailDialog.data.transfer?.fromWarehouseId) }}</span>
              </div>
              <div class="summary-item">
                <span class="label">调入仓库：</span>
                <span>{{ getWarehouseName(auditDetailDialog.data.transfer?.toWarehouseId) }}</span>
              </div>
              <div class="summary-item">
                <span class="label">调拨类型：</span>
                <span>{{ auditDetailDialog.data.transfer?.transferType || '-' }}</span>
              </div>
            </div>
            <div class="summary-row">
              <div class="summary-item">
                <span class="label">创建人：</span>
                <span>{{ auditDetailDialog.data.transfer?.createdBy }}</span>
              </div>
              <div class="summary-item">
                <span class="label">调拨日期：</span>
                <span>{{ formatDate(auditDetailDialog.data.transfer?.transferDate) }}</span>
              </div>
              <div class="summary-item">
                <span class="label">提交时间：</span>
                <span>{{ formatDate(auditDetailDialog.data.transfer?.createdAt) }}</span>
              </div>
            </div>
          </div>

          <!-- 调拨汇总 -->
          <div class="transfer-summary">
            <h4>调拨汇总</h4>
            <div class="transfer-stats">
              <div class="transfer-stat">
                <div class="transfer-number">{{ getItemCount() }}</div>
                <div class="transfer-label">调拨商品数</div>
              </div>
              <div class="transfer-stat">
                <div class="transfer-number">¥{{ formatAmount(getTotalAmount()) }}</div>
                <div class="transfer-label">调拨总金额</div>
              </div>
              <div class="transfer-stat">
                <div class="transfer-number">{{ getBatchCount() }}</div>
                <div class="transfer-label">涉及批次</div>
              </div>
            </div>
          </div>

          <!-- 调拨明细 -->
          <div class="audit-details">
            <h4>调拨明细</h4>
            <table class="data-table">
              <thead>
                <tr>
                  <th>商品名称</th>
                  <th>商品编码</th>
                  <th>调拨数量</th>
                  <th>单价</th>
                  <th>总金额</th>
                  <th>批次号</th>
                  <th>有效期</th>
                  <th>备注</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in auditDetailDialog.data.items || []" :key="index">
                  <td>{{ getProductName(item.skuId) }}</td>
                  <td>{{ getSkuCode(item.skuId) }}</td>
                  <td>{{ item.qty }}</td>
                  <td>¥{{ item.unitPrice }}</td>
                  <td>¥{{ item.totalAmount }}</td>
                  <td>{{ item.batchNo || '-' }}</td>
                  <td>{{ formatDate(item.expiryDate) }}</td>
                  <td>{{ item.remark || '-' }}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- 审核意见 -->
          <div class="audit-opinion">
            <h4>审核意见</h4>
            <textarea v-model="auditDetailDialog.opinion" placeholder="请输入审核意见..." rows="3"></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="auditDetailDialog.visible = false">关闭</button>
          <button class="btn btn-danger" @click="handleDetailReject">驳回</button>
          <button class="btn btn-success" @click="handleDetailApprove">审核通过</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { apiGet, apiPost } from '../../utils/api.js'

// 响应式数据
const auditList = ref([])
const warehouses = ref([])
const products = ref([])
let searchTimeout = null

// 搜索表单
const searchForm = reactive({
  transferCode: '',
  fromWarehouseId: '',
  toWarehouseId: '',
  transferType: '',
  createdBy: '',
  submitDate: ''
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 审核详情对话框
const auditDetailDialog = reactive({
  visible: false,
  loading: false,
  data: {},
  opinion: '',
  currentItem: null
})

// 统计数据
const totalItems = computed(() => {
  return auditList.value.reduce((sum, item) => sum + (item.itemCount || 0), 0)
})

const totalAmount = computed(() => {
  return auditList.value.reduce((sum, item) => sum + (item.totalAmount || 0), 0)
})

// 计算可见页码
const visiblePages = computed(() => {
  const currentPage = pagination.current
  const totalPages = Math.ceil(pagination.total / pagination.size)
  
  if (totalPages <= 5) {
    return Array.from({ length: totalPages }, (_, i) => i + 1)
  }
  
  if (currentPage <= 3) {
    return [1, 2, 3, 4, 5]
  }
  
  if (currentPage >= totalPages - 2) {
    return [totalPages - 4, totalPages - 3, totalPages - 2, totalPages - 1, totalPages]
  }
  
  return [currentPage - 2, currentPage - 1, currentPage, currentPage + 1, currentPage + 2]
})

// 获取待审核调拨单列表
const fetchAuditList = async () => {
  try {
    const params = new URLSearchParams({
        page: pagination.current,
        size: pagination.size,
        status: 1, // 只查询待审核状态的调拨单
      ...(searchForm.transferCode && { transferCode: searchForm.transferCode }),
      ...(searchForm.fromWarehouseId && { fromWarehouseId: searchForm.fromWarehouseId }),
      ...(searchForm.toWarehouseId && { toWarehouseId: searchForm.toWarehouseId }),
      ...(searchForm.transferType && { transferType: searchForm.transferType }),
      ...(searchForm.createdBy && { createdBy: searchForm.createdBy })
    })

    const data = await apiGet(`/ware-service/ware/transfer?${params}`)
    
    if (data.data && data.data.records) {
      auditList.value = data.data.records.map(item => ({
        ...item,
        selected: false,
        itemCount: Math.floor(Math.random() * 10) + 1, // 模拟商品数量
        totalAmount: (Math.random() * 10000) + 1000, // 模拟总金额
        priority: Math.floor(Math.random() * 3) + 1, // 1-低, 2-中, 3-高
      }))
      pagination.total = data.data.total || 0
      pagination.current = data.data.current || 1
    } else {
      auditList.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取待审核调拨单列表失败:', error)
    auditList.value = []
    pagination.total = 0
  }
}

// 实时搜索输入处理
const onSearchInput = () => {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  
  searchTimeout = setTimeout(() => {
    pagination.current = 1
    fetchAuditList()
  }, 500)
}

// 重置搜索
const resetSearch = () => {
  searchForm.transferCode = ''
  searchForm.fromWarehouseId = ''
  searchForm.toWarehouseId = ''
  searchForm.transferType = ''
  searchForm.createdBy = ''
  searchForm.submitDate = ''
  pagination.current = 1
  fetchAuditList()
}

// 页码切换
const changePage = (page) => {
  if (page < 1 || page > Math.ceil(pagination.total / pagination.size)) return
  pagination.current = page
  fetchAuditList()
}

// 审核操作
const handleAudit = async (row) => {
  auditDetailDialog.visible = true
  auditDetailDialog.loading = true
  auditDetailDialog.data = {}
  auditDetailDialog.opinion = ''
  auditDetailDialog.currentItem = row
  
  try {
    const result = await apiGet(`/ware-service/ware/transfer/${row.id}`)
    auditDetailDialog.data = result.data || {}
  } catch (error) {
    console.error('获取调拨详情失败:', error)
  } finally {
    auditDetailDialog.loading = false
  }
}

// 详情审核通过
const handleDetailApprove = async () => {
  try {
    const id = auditDetailDialog.data.transfer?.id
    
    const result = await apiPost(`/ware-service/ware/transfer/${id}/approve`)
    if (result && (result.code === 0 || result.status === 200 || result.success)) {
      alert('审核通过成功')
      auditDetailDialog.visible = false
      await fetchAuditList()
    } else {
      alert('审核失败')
    }
  } catch (error) {
    console.error('审核失败:', error)
    alert('审核失败')
  }
}

// 详情驳回
const handleDetailReject = async () => {
  if (!auditDetailDialog.opinion.trim()) {
    alert('请输入驳回意见')
    return
  }
  
  try {
    const id = auditDetailDialog.data.transfer?.id
    const result = await apiPost(`/ware-service/ware/transfer/${id}/reject`, {
      opinion: auditDetailDialog.opinion
    })
    
    if (result && (result.code === 0 || result.status === 200 || result.success)) {
      alert('调拨单已驳回')
      auditDetailDialog.visible = false
      await fetchAuditList()
    } else {
      alert('驳回失败')
    }
  } catch (error) {
    console.error('驳回失败:', error)
    alert('驳回失败')
  }
}

// 获取仓库列表
const fetchWarehouses = async () => {
  try {
    const params = new URLSearchParams({
      page: 1,
      size: 100
    })
    
    const data = await apiGet(`/ware-service/warehouse/list?${params}`)
    
    if (data.records) {
      warehouses.value = data.records || []
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    warehouses.value = []
  }
}

// 获取商品列表
const fetchProducts = async () => {
  try {
    const params = new URLSearchParams({
      page: 1,
      size: 100
    })
    
    const data = await apiGet(`/ware-service/ware/sku/list?${params}`)
    
    if (data.records) {
      products.value = data.records || []
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    products.value = []
  }
}

// 工具方法
const getWarehouseName = (id) => {
  if (!id) return '-'
  const warehouse = warehouses.value.find(w => w.id === id)
  return warehouse ? warehouse.whName : '-'
}

const getProductName = (skuId) => {
  const product = products.value.find(p => p.id === skuId)
  return product ? product.productName : '未知商品'
}

const getSkuCode = (skuId) => {
  const product = products.value.find(p => p.id === skuId)
  return product ? product.skuCode : '-'
}

const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString()
}

const formatAmount = (amount) => {
  if (!amount) return '0.00'
  return Number(amount).toFixed(2)
}

const getPriorityText = (priority) => {
  const priorityMap = { 1: '低', 2: '中', 3: '高' }
  return priorityMap[priority] || '中'
}

const getPriorityClass = (priority) => {
  const classMap = { 1: 'priority-low', 2: 'priority-medium', 3: 'priority-high' }
  return `priority ${classMap[priority] || 'priority-medium'}`
}

// 调拨统计方法
const getItemCount = () => {
  const items = auditDetailDialog.data.items || []
  return items.length
}

const getTotalAmount = () => {
  const items = auditDetailDialog.data.items || []
  return items.reduce((sum, item) => sum + (Number(item.totalAmount) || 0), 0)
}

const getBatchCount = () => {
  const items = auditDetailDialog.data.items || []
  const batches = new Set(items.map(item => item.batchNo).filter(Boolean))
  return batches.size
}

// 生命周期
onMounted(() => {
  fetchAuditList()
  fetchWarehouses()
  fetchProducts()
})
</script>

<style scoped>
.order-payment {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.breadcrumb {
  color: #666;
  font-size: 14px;
}

.search-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 16px;
}

.form-item {
  display: flex;
  flex-direction: column;
  min-width: 180px;
}

.form-item label {
  font-size: 14px;
  margin-bottom: 5px;
  color: #333;
}

.form-item input,
.form-item select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-buttons {
  display: flex;
  gap: 10px;
  align-items: flex-end;
  margin-top: 24px;
}

/* 审核说明区域 */
.audit-info-bar {
  background: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 6px;
  padding: 16px 20px;
  margin-bottom: 20px;
}

.info-text {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #333;
}

.info-icon {
  font-size: 16px;
}

/* 统计卡片 - 审核主题色 */
.stats-section {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 20px;
}

.stat-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
}

.stat-card.audit {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

.table-container {
  margin-bottom: 20px;
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  border: 1px solid #ddd;
  padding: 10px;
  text-align: left;
}

.data-table th {
  background-color: #f8f9fa;
  font-weight: bold;
}

.data-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

.row-selected {
  background-color: #e6f7ff !important;
}

.text-center {
  text-align: center;
}

.text-success {
  color: #52c41a;
  font-weight: 500;
}

.text-danger {
  color: #ff4d4f;
  font-weight: 500;
}

.text-warning {
  color: #fa8c16;
  font-weight: 500;
}

/* 调拨单号样式 */
.transfer-code {
  font-weight: 500;
  color: #333;
}

.transfer-meta {
  font-size: 12px;
  color: #999;
}

/* 优先级样式 */
.priority {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.priority-low {
  background-color: #f0f0f0;
  color: #666;
}

.priority-medium {
  background-color: #fff7e6;
  color: #fa8c16;
}

.priority-high {
  background-color: #fff2f0;
  color: #ff4d4f;
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.pagination-controls {
  display: flex;
  gap: 5px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-primary {
  background-color: #1890ff;
  color: white;
}

.btn-secondary {
  background-color: #f5f5f5;
  color: #333;
}

.btn-success {
  background-color: #52c41a;
  color: white;
}

.btn-info {
  background-color: #1890ff;
  color: white;
}

.btn-danger {
  background-color: #ff4d4f;
  color: white;
}

.btn-small {
  padding: 4px 8px;
  font-size: 12px;
}

.btn-page {
  padding: 4px 10px;
  min-width: 30px;
  background-color: #fff;
  border: 1px solid #ddd;
}

.btn-page.active {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-content.audit-modal {
  width: 1200px;
  max-width: 95vw;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #ddd;
}

.modal-header h3 {
  margin: 0;
}

.modal-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
}

.modal-body {
  padding: 20px;
}

.modal-footer {
  padding: 16px 20px;
  border-top: 1px solid #ddd;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 审核详情样式 */
.audit-summary {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.summary-row {
  display: flex;
  gap: 30px;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.summary-row:last-child {
  margin-bottom: 0;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.summary-item .label {
  font-weight: bold;
  color: #666;
}

/* 调拨汇总 */
.transfer-summary {
  margin-bottom: 20px;
}

.transfer-summary h4 {
  margin-bottom: 12px;
  color: #333;
}

.transfer-stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.transfer-stat {
  text-align: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.transfer-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.transfer-label {
  font-size: 12px;
  color: #666;
}

/* 审核详情 */
.audit-details {
  margin-bottom: 20px;
}

.audit-details h4 {
  margin-bottom: 12px;
  color: #333;
}

/* 审核意见 */
.audit-opinion {
  margin-bottom: 20px;
}

.audit-opinion h4 {
  margin-bottom: 12px;
  color: #333;
}

.audit-opinion textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
  font-family: inherit;
}
</style>
